package jsu.hx.lost.Controller;

import jsu.hx.lost.Model.dto.FindItemDTO;
import jsu.hx.lost.Model.dto.LostItemDTO;
import jsu.hx.lost.Model.vo.PageResult;
import jsu.hx.lost.Service.FindItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/find")
public class FindController {

    @Autowired
    private FindItemService findItemService;

    // 查询所有记录
    @GetMapping("/all")
    public ResponseEntity<List<FindItemDTO>> getAllFindItems() {
        List<FindItemDTO> items = findItemService.getAllFindItems();
        return ResponseEntity.ok(items);
    }

    // 根据ID查询
    @GetMapping("/ById/{id}")
    public ResponseEntity<FindItemDTO> getFindItemById(@PathVariable Long id) {
        FindItemDTO item = findItemService.getFindItemById(id);
        return item != null ? ResponseEntity.ok(item) : ResponseEntity.notFound().build();
    }

    // 添加记录
    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> addFindItem(
            @RequestParam("itemName") String itemName,
            @RequestParam("itemCategory") String itemCategory,
            @RequestParam("foundLocation") String foundLocation,
            @RequestParam("locate") String locate,
            @RequestParam("foundTime") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date foundTime,
            @RequestParam("detailedDescription") String detailedDescription,
            @RequestParam(value = "image",required = false) MultipartFile imageFile) {
        Map<String, Object> response = findItemService.addFindItem(
                itemName, itemCategory, foundLocation,locate, foundTime,detailedDescription, imageFile
        );
        return wrapServiceResponse(response);
    }

    // 更新记录
    @PutMapping(value = "/update/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<Map<String, Object>> updateFindItem(
            @PathVariable Long id,
            @RequestParam(value = "image", required = false) MultipartFile imageFile,
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String itemCategory,
            @RequestParam(required = false) String foundLocation,
            @RequestParam(required = false) String locate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date foundTime,
            @RequestParam(required = false) String detailedDescription) {
        Map<String, Object> response = findItemService.updateFindItem(
                id, imageFile, itemName, itemCategory, foundLocation, locate,foundTime, detailedDescription
        );
        return wrapServiceResponse(response);
    }

    // 逻辑删除记录
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteFindItem(@PathVariable Long id) {
        String result = findItemService.deleteFindItem(id);
        return result.contains("success") ?
                ResponseEntity.ok(result) :
                ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
    }

    // 查询当前用户的记录
    @GetMapping("/myItems")
    public ResponseEntity<Map<String, Object>> getMyFindItems() {
        Map<String, Object> response = findItemService.getMyFindItems();
        return wrapServiceResponse(response);
    }

    // 模糊搜索
    @GetMapping("/search")
    public ResponseEntity<List<FindItemDTO>> fuzzySearch(
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String foundLocation,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date foundTime,
            @RequestParam(required = false) String username) { // 新增用户名参数
        List<FindItemDTO> items = findItemService.fuzzySearch(itemName, foundLocation, foundTime, username);
        return ResponseEntity.ok(items);
    }

    // 分页查询
    @GetMapping("/page")
    public ResponseEntity<PageResult<FindItemDTO>> getFindItemsByPage(
            @RequestParam int page,
            @RequestParam int pageSize,
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String foundLocation,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date foundTime,
            @RequestParam(required = false) String username, // 新增用户名参数
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortOrder) {

        log.info("接收分页请求: page={}, size={}, itemName={}, foundLocation={}, foundTime={}, username={}, sortField={}, sortOrder={}",
                page, pageSize, itemName, foundLocation, foundTime, username, sortField, sortOrder);

        PageResult<FindItemDTO> result = findItemService.getFindItemsByPage(
                page, pageSize, itemName, foundLocation, foundTime, username, sortField, sortOrder); // 传入新参数

        return ResponseEntity.ok(result);
    }
    // LostController.java
    @GetMapping("/latest")
    public ResponseEntity<Map<String, Object>> getLatestFoundItems(
            @RequestParam(defaultValue = "3") int limit
    ) {
        List<FindItemDTO> items = findItemService.getLatestFoundItems(limit);
        Map<String, Object> response = new HashMap<>();
        response.put("data", items);
        return ResponseEntity.ok(response);
    }
    @GetMapping("/export")
    public ResponseEntity<byte[]> exportToExcel(
            @RequestParam(required = false) String itemName,
            @RequestParam(required = false) String foundLocation,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date foundTime,
            @RequestParam(required = false) String username) {
        try {
            // 根据查询条件获取数据
            List<FindItemDTO> items = findItemService.fuzzySearch(
                    itemName, foundLocation, foundTime, username
            );

            // 导出为Excel
            ByteArrayOutputStream stream = findItemService.exportToExcel(items);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            String encodedFilename = URLEncoder.encode("失物数据.xlsx", StandardCharsets.UTF_8.name());
            headers.setContentDispositionFormData("attachment", encodedFilename);

            return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            log.error("导出Excel失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
//    public ResponseEntity<byte[]> exportToExcel() {
//        try {
//            // 获取所有数据
//            List<FindItemDTO> items = findItemService.getAllFindItems();
//
//            // 导出为Excel
//            ByteArrayOutputStream stream = findItemService.exportToExcel(items);
//
//            // 设置响应头
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//
//            // 对文件名进行 URL 编码处理
//            String encodedFilename = URLEncoder.encode("招领数据.xlsx", StandardCharsets.UTF_8.name());
//            headers.setContentDispositionFormData("attachment", encodedFilename);
//
//            return new ResponseEntity<>(stream.toByteArray(), headers, HttpStatus.OK);
//        } catch (Exception e) {
//            log.error("导出Excel失败: {}", e.getMessage());
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
//        }
//    }
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importFromExcel(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();
        try {
            int count = findItemService.importFromExcel(file);
            response.put("status", "success");
            response.put("message", "成功导入 " + count + " 条数据");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("status", "error");
            response.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }
    // 统一封装服务层响应为ResponseEntity
    private ResponseEntity<Map<String, Object>> wrapServiceResponse(Map<String, Object> serviceResponse) {
        String status = (String) serviceResponse.get("status");
        Object message = serviceResponse.get("message");

        if ("success".equals(status)) {
            return ResponseEntity.ok(serviceResponse);
        } else {
            switch ((String) message) {
                case "用户未认证":
                case "无效的用户ID":
                    return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(serviceResponse);
                case "指定ID的记录不存在":
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(serviceResponse);
                case "图片保存失败":
                case "文件处理失败":
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(serviceResponse);
                default:
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(serviceResponse);
            }
        }
    }
}